package com.sinoglobal.sinostore.fragment;

import andbase.listener.AbOnListViewListener;
import andbase.view.pullview.AbPullListView;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.sinoglobal.sinostore.R;
import com.sinoglobal.sinostore.activity.GoodsDetailActivity;
import com.sinoglobal.sinostore.activity.SecondKillActivity;
import com.sinoglobal.sinostore.adapter.SecondKillGoodsAdapter;
import com.sinoglobal.sinostore.bean.SecondKillListVo;
import com.sinoglobal.sinostore.bean.SecondKillListVo.SecondKillVo;
import com.sinoglobal.sinostore.system.Constants;
/**
 * 
* @title: SecondKillFragment.java 
* @package com.chiliring.sinostore.fragment 
* @description: TODO(秒杀列表) 
* @author LK
* @date 2015-1-13 下午4:38:16
 */
@SuppressLint("ValidFragment")
public class SecondKillFragment extends Fragment implements AbOnListViewListener,OnItemClickListener{
	/**未开始**/
	private static final int NOTATTHE = 1;
	/**抢购中**/
	private static final int SNAPINUP = 2;
	/**结束**/
	private static final int ENDOFTHE = 3;
	
	/**抢购的状态**/
	private TextView tvShopState;
	
	/**计时提示**/
	private TextView tvCountdownPrompt;
	
	/**计时器布局**/
	private LinearLayout llCountdown;
	private TextView tvHour;
	private TextView tvMinutes;
	private TextView tvSeconds;
	/**计时器**/
//	private CustomDigitalClock customDownTime;
	
	/**秒杀订单布局**/
	private AbPullListView lvSecoundkillList;
	
	/**秒杀商品Adapter**/
	private SecondKillGoodsAdapter killGoodsAdapter;
	
	
	/**当前页**/
	private int pageNum = 0;
	/**活动id**/
	private  String activityId;
	
	private Handler mHandler;
	
	private Runnable runnable;
	
	private SecondKillListVo entity;
	
	private View secondKillView;
	
	/**计时**/
	private int timing;
	
	/**倒计时时间**/
	private long customTime;
	
	private SecondKillActivity secondKillActivity;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		activityId = getArguments().getString("activityId");
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		secondKillView = inflater.inflate(R.layout.shop_fragment_secondkill_layout, null);
		initView(secondKillView);
		secondKillView.setVisibility(View.INVISIBLE);
		initData();
		return secondKillView;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		pageNum=0;
		lvSecoundkillList.setPullLoadEnable(true);
		loadData();
	}
	
	private void initView(View view){
		tvShopState = (TextView)view.findViewById(R.id.tv_shop_state);
		tvCountdownPrompt = (TextView)view.findViewById(R.id.tv_countdown_prompt);
		llCountdown = (LinearLayout)view.findViewById(R.id.ll_countdown);
		tvHour = (TextView)view.findViewById(R.id.tv_hour);
		tvMinutes = (TextView)view.findViewById(R.id.tv_minutes);
		tvSeconds = (TextView)view.findViewById(R.id.tv_second);
		lvSecoundkillList = (AbPullListView)view.findViewById(R.id.lv_secoundkill_list);
		
		lvSecoundkillList.setAbOnListViewListener(this);
		lvSecoundkillList.setPullRefreshEnable(true);
		lvSecoundkillList.setOnItemClickListener(this);
	}
	
	public SecondKillFragment(){
		super();
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}
	
	private void initData(){
		if(null != secondKillActivity){
			killGoodsAdapter = new SecondKillGoodsAdapter(secondKillActivity);
			lvSecoundkillList.setAdapter(killGoodsAdapter);
		}
	}
	
	public static SecondKillFragment newInstance(int position, String id) {
		SecondKillFragment f = new SecondKillFragment();
		Bundle bundle = new Bundle();
		bundle.putString("activityId", id);
		f.setArguments(bundle);
		return f;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		secondKillActivity = (SecondKillActivity)activity;
	} 
	
	/**
	 * 
	* @author LK
	* @methods loadData 
	* @description 描述信息  加载数据
	* @date 2015-1-19 下午2:23:33 参数说明
	 */
	private void loadData(){
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("por","602");
		params.addQueryStringParameter("proIden",Constants.STOREFLAG);
		params.addQueryStringParameter("id",activityId);
		params.addQueryStringParameter("pageNum",String.valueOf(pageNum));
		params.addQueryStringParameter("pageSize","10");
		httpUtils.send(HttpMethod.POST, Constants.STORE_URL, params, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				secondKillView.setVisibility(View.VISIBLE);
				String result = responseInfo.result;
				LogUtils.i("result="+result);
				if(!TextUtils.isEmpty(result)){
					try {
						entity = JSON.parseObject(result, SecondKillListVo.class);
					} catch (Exception e) {
						Toast.makeText(getActivity(), "系统异常，请重试", Toast.LENGTH_SHORT).show();
					}
					if(null != entity){
						if(Constants.STORE_SUCCESS_CODE.equals(entity.getCode())){
							Constants.PIC_HOST = entity.getHost();
							stopLoadData();
								if(pageNum == 0){
									activityState();
									killGoodsAdapter.clearData();
									lvSecoundkillList.setPullLoadEnable(true);
								}
								killGoodsAdapter.AddData(entity.list);
								if(entity.list.size()<10){
									lvSecoundkillList.setPullLoadEnable(false);
								}
						}
					}
				}
			}
		});
	}

	@Override
	public void onRefresh() {
		pageNum = 0;
		loadData();
	}

	@Override
	public void onLoadMore() {
		pageNum ++;
		loadData();
	}
	
	private void stopLoadData(){
		lvSecoundkillList.stopLoadMore();
		lvSecoundkillList.stopRefresh();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		SecondKillVo secondKillVo = (SecondKillVo)killGoodsAdapter.getItem(position-1);
		if(ENDOFTHE == entity.status){
			Toast.makeText(getActivity(), "活动已结束", Toast.LENGTH_SHORT).show();
			return;
		}
		if(!Constants.SOLDOUT.equals(secondKillVo.status)){
			Bundle bundle = new Bundle();
			bundle.putString("goodsId", secondKillVo.id);
			bundle.putString("activityId", activityId);
			Intent intent = new Intent(getActivity(),GoodsDetailActivity.class);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}
	/**
	 * 
	* @author LK
	* @methods activityState 
	* @description 更新活动时间
	* @date 2015-2-4 上午11:03:02 参数说明
	 */
	private void activityState(){
		switch (entity.status) {
		//未开始
		case NOTATTHE:
			tvShopState.setText("即将开始");
			tvCountdownPrompt.setText("距离本场开始");
			if(isOK(entity.end_time)){
				llCountdown.setVisibility(View.GONE);
				tvCountdownPrompt.setText(String.format("%s开始", entity.end_time));
			}else{
				customTime = Long.parseLong(entity.end_time);
				customClock();
			}
			break;
		//抢购中
		case SNAPINUP:
			tvShopState.setText("抢购中");
			if(isOK(entity.end_time)){
				llCountdown.setVisibility(View.GONE);
				tvCountdownPrompt.setText(String.format("距离本场结束  %s", entity.end_time));
			}else{
				tvCountdownPrompt.setText("距离本场结束");
				customTime = Long.parseLong(entity.end_time);
				customClock();
			}
			break;
		//结束
		case ENDOFTHE:
			tvShopState.setText("已结束");
			tvCountdownPrompt.setVisibility(View.GONE);
			llCountdown.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}
	
	/**
	* @author LK
	* @methods customClock 
	* @description 倒计时
	* @date 2015-2-4 上午11:01:05 参数说明
	 */
	private void customClock(){
		timing = 0;
		if(null == mHandler && null == runnable){
			mHandler = new Handler();
			runnable = new Runnable() {
				@Override
				public void run() {
					long tempTime = customTime;
					tempTime = tempTime - (timing++);
					if(tempTime < 0){
						timing = 0;
						dealState();
					}else{
						dealTime(tempTime);
					}
					long now = SystemClock.uptimeMillis();
					long next = now + (1000 - now % 1000);
					mHandler.postAtTime(runnable, next);
				}
			};
			runnable.run();
		}
	}
	
	/**
	 * 
	* @author LK
	* @methods dealState 
	* @description 处理时间状态
	* @date 2015-2-4 上午11:16:47 参数说明
	 */
	private void dealState(){
		switch (entity.status) {
		case NOTATTHE:
			entity.end_time = String.valueOf(Long.parseLong(entity.act_end_time) - Long.parseLong(entity.act_start_time));
			entity.status = SNAPINUP;
			activityState();
			break;
		case SNAPINUP:
			entity.status = ENDOFTHE;
			activityState();
			break;
		case ENDOFTHE:
			break;
		default:
			break;
		}
	}


	private void dealTime(long time) {
		long day = time / (24 * 60 * 60);
		long hours = (time % (24 * 60 * 60)) / (60 * 60);
		long minutes = ((time % (24 * 60 * 60)) % (60 * 60)) / 60;
		long second = ((time % (24 * 60 * 60)) % (60 * 60)) % 60;
		String hoursStr = timeStrFormat(String.valueOf(hours));
		String minutesStr = timeStrFormat(String.valueOf(minutes));
		String secondStr = timeStrFormat(String.valueOf(second));
		tvHour.setText(hoursStr);
		tvMinutes.setText(minutesStr);
		tvSeconds.setText(secondStr);
	}

	private static String timeStrFormat(String timeStr) {
		switch (timeStr.length()) {
		case 1:
			timeStr = "0" + timeStr;
			break;
		}
		return timeStr;
	}
	/**
	 * 
	 * @author LK
	 * @methods isOK 
	 * @description 描述信息 验证是否是日期格式
	 * @date 2015-1-21 上午11:09:13
	 * @param str
	 * @return 参数说明
	 */
	public boolean isOK(String str) {
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		try {
			format.parse(str);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

}
